package com.zhijs.struts.action;

import static java.lang.System.out;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.map.MultiValueMap;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.h819.core.commons.MyCollectionUtils;
import com.h819.core.db.MyDbUtils;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * 
 * @Title: GoAction.java
 * @Description: TODO(添加描述)
 * @author H819
 * @date 2010-3-29
 * @version V1.0
 * 
 */

public class GoAction extends ActionSupport implements SessionAware,
		ServletRequestAware {

	Logger log = Logger.getLogger(GoAction.class);
	private QueryRunner runner = new QueryRunner();;
	private Connection conn = MyDbUtils.getInstance("h819.properties").getOracleConnection235();
	private Map session;

	private HttpServletRequest request;
	private String id = "";
	private String action = "";

	private String textadress = "pdfpath";

	// resultdata
	private List<MultiValueMap> newSearchDataInSession = null;

	/**
	 * 下载文件。用动态方法解析本类。调用：downLoadFileAction
	 * 
	 * @return
	 * @throws Exception
	 */
	// 访问方法 downLoadFileAction.action
	public String downLoadFile() throws Exception {

		// 初始化 session
		initSessionValue();

		// 测试传过来的数据
		log.info(StringUtils.center("session 中的数据", 40, "="));
		for (MultiValueMap m : newSearchDataInSession) {
			for (Iterator it = m.entrySet().iterator(); it.hasNext();) {
				Map.Entry entry = (Map.Entry) it.next();
				Object key = entry.getKey();
				Object value = entry.getValue();
				out.println(key + " = " + value);
			}
		}

		// 把文件路径放入 session 中
		String temps = getValueFromSession("ZHIJS_NEW_TEXT_ADDRESS");
		if (temps != null && this.getAction().equals("newlist")) {
			log.info("newlist :" + temps);
			session.put(textadress, temps);
		}

		// 查询是否有更新信息时，旧标准地址
		temps = getValueFromSession("ZHIJS_TEXT_ADDRESS");
		if (temps != null && this.getAction().equals("oldlist")) {
			log.info("oldlist :" + temps);
			session.put(textadress, temps);
		}

		// 查询是否有更新信息时，旧标准修改单地址
		temps = getValueFromSession("");
		if (temps != null && this.getAction().equals("oldmodifylist")) {// ??
			// 功能还未实现
			log.info("oldmodifylist :" + temps);
			session.put(textadress, temps);
		}

		// 按照部门检索时，文件地址
		temps = getValueFromSession("ST_STANDARD_TEXT_ADDRESS");
		if (temps != null && this.getAction().equals("bydepartmentfile")) {
			log.info("ST_STANDARD_TEXT_ADDRESS :" + temps);
			session.put(textadress, temps);
		}

		// 按照部门检索时，修改单地址
		temps = getValueFromSession("FILE_ADDRESS");
		if (temps != null && this.getAction().equals("bydepartmentmodify")) {
			log.info("FILE_ADDRESS :" + temps);
			session.put(textadress, temps);
		}
		
		// 按照部门检索时，修改单地址
		temps = getValueFromSession("TEXT_ADDRESS");
		if (temps != null && this.getAction().equals("modifystdfile")) {
			log.info("TEXT_ADDRESS :" + temps);
			session.put(textadress, temps);
		}
		
		
		// 按照部门检索时，修改单地址
		temps = getValueFromSession("FILE_ADDRESS");
		if (temps != null && this.getAction().equals("modifyfile")) {
			log.info("FILE_ADDRESS :" + temps);
			session.put(textadress, temps);
		}
		
		

		// // 把文件路径放入 session 中
		// // 查询是否有更新信息时，新标准地址
		// Object temp = MyCollectionUtils.getSingleValue(mapTextAddress
		// .getCollection("ZHIJS_NEW_TEXT_ADDRESS"));
		//		
		// if(this.getValue("ZHIJS_NEW_TEXT_ADDRESS"))!=null)
		//		
		// log.info("newlist :" + temp);
		// if (temp != null && this.getAction().equals("newlist"))
		// session.put(textadress, temp.toString());
		//
		// // 查询是否有更新信息时，旧标准地址
		// temp = MyCollectionUtils.getSingleValue(mapTextAddress
		// .getCollection("ZHIJS_TEXT_ADDRESS"));
		// log.info("oldlist :" + temp);
		// if (temp != null && this.getAction().equals("oldlist"))
		// session.put(textadress, temp.toString());
		//
		// // 查询是否有更新信息时，旧标准修改单地址
		// temp = MyCollectionUtils.getSingleValue(mapTextAddress
		// .getCollection(" "));
		// log.info("oldmodifylist :" + temp);
		// if (temp != null && this.getAction().equals("oldmodifylist"))//
		// 修改单下载???
		// // 地址没有读取
		// session.put(textadress, temp.toString());
		//
		// // 按照部门检索时，文件地址
		// temp = MyCollectionUtils.getSingleValue(mapTextAddress
		// .getCollection("ST_STANDARD_TEXT_ADDRESS"));
		// log.info("bydepartmentfile :" + temp);
		// if (temp != null && this.getAction().equals("bydepartmentfile"))
		// session.put(textadress, temp.toString());
		//
		// // 按照部门检索时，修改单地址
		// temp = MyCollectionUtils.getSingleValue(mapTextAddress
		// .getCollection("FILE_ADDRESS"));
		// log.info("bydepartmentmodify :" + temp);
		// if (temp != null && this.getAction().equals("bydepartmentmodify"))
		// session.put(textadress, temp.toString());
		//		
	
		
		// 配置文件中的 result
		return "downLoadFile";
		// return null;
	}

	/**
	 * 更新托管标准为最新标准
	 * @return
	 * @throws Exception
	 */
	public String updateStandard() throws Exception {

		// 初始化 session
		initSessionValue();

		// 得到标准号和部门编号，即可更新
		// Connection conn = MyDbUtils.getInstance().getOracleConnection235();
		// QueryRunner runner = new QueryRunner();

		String standard_code = "";
		String standard_new_code = "";
		String department_code = "";

		String temp = getValueFromSession("ZHIJS_STTANDARDCODE");
		if (temp != null) {
			standard_code = temp;
			log.info("standard_code :" + standard_code);
		}

		temp = getValueFromSession("ZHIJS_DEPARTMENTCODE");
		if (temp != null) {
			department_code = temp;
			log.info("ZHIJS_DEPARTMENTCODE :" + department_code);
		}

		temp = getValueFromSession("ZHIJS_NEW_STANDARDCODE");
		if (temp != null) {
			standard_new_code = temp;
			log.info("standard_new_code :" + standard_new_code);
		}

		String searchSql = "select count(1) from zhijs_standard where st_standardcode ='"
				+ standard_new_code
				+ "' and st_department='"
				+ department_code
				+ "'";

		String updateSql = "update zhijs_standard set st_standardcode ='"
				+ standard_new_code
				+ "',st_lastupdate = sysdate where st_standardcode = '"
				+ standard_code + "' and st_department = '" + department_code
				+ "';";

		log.info("searchSql :" + searchSql);
		log.info("updateSql :" + updateSql);

		// 如果已经有了记录，删除旧的。因为新的可能代替了几个旧的，所以应该删除旧的
		// 否则修改
		
		//下个版本，不删除，只一个标记，记录所有托管过的标准，保留历史
		Map<String, Object> searchResult;
		try {
			searchResult = runner.query(conn, searchSql, new MapHandler());

			if (searchResult != null)// 跳过
			{
				for (Iterator it = searchResult.entrySet().iterator(); it
						.hasNext();) {
					Map.Entry entry = (Map.Entry) it.next();
					System.out.println(entry.getKey() + " = "
							+ entry.getValue());
				}

				String delSql = "delete from zhijs_standard where st_standardcode = '"
						+ standard_code
						+ "'"
						+ " and st_department='"
						+ department_code + "'";

				log.info("delSql: " + delSql);
				runner.update(conn, delSql);

			}

			else // 更新
			{
				log.info("excute updateSql .");
				runner.update(conn, updateSql);
			}

		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}

		return "updateStandard";

	}

	/**
	 * 更新修改单托管表，标记为已托管
	 * @return
	 * @throws Exception
	 */
	public String updateMofify() throws Exception {

		// 初始化 session
		initSessionValue();

		String standard_code = "";
		String modify_number = "";
		String department_code = "";

		String temp = getValueFromSession("ST_STANDARDCODE");
		if (temp != null) {
			standard_code = temp;
			log.info("ST_STANDARDCODE :" + standard_code);
		}

		temp = getValueFromSession("ZHIJS_DEPARTMENTCODE");
		if (temp != null) {
			department_code = temp;
			log.info("ZHIJS_DEPARTMENTCODE :" + department_code);
		}

		temp = getValueFromSession("MODIFY_NUMBER");
		if (temp != null) {
			modify_number = temp;
			log.info("MODIFY_NUMBER :" + modify_number);
		}

		String searchModSql = "select * from zhijs_xgd xgd where xgd.standard_code='"+standard_code+"' " +
				"and xgd.department_code='"+department_code+"' " +
						"and xgd.modify_number ='"+modify_number+"'";

		String updateModSql = "insert into zhijs_xgd(id,standard_code,department_code,modify_number,updatetime,modfyuser) values (zhijs_seq.nextval," +
				"'"+standard_code+"'," +
				"'"+department_code+"'," +
				"'"+modify_number+"',sysdate," +
				"'zhijs')";

		log.info("searchSql :" + searchModSql);
		log.info("updateSql :" + updateModSql);

		// 如果已经有了记录，删除旧的。因为新的可能代替了几个旧的，所以应该删除旧的
		// 否则修改
		
		//下个版本，不删除，只一个标记，记录所有托管过的标准，保留历史
		Map<String, Object> searchResult;
		try {
			searchResult = runner.query(conn, searchModSql, new MapHandler());

			if (searchResult != null)// 跳过
			{
				for (Iterator it = searchResult.entrySet().iterator(); it
						.hasNext();) {
					Map.Entry entry = (Map.Entry) it.next();
					System.out.println(entry.getKey() + " = "
							+ entry.getValue());
				}
			}

			else // 更新
			{
				log.info("excute updateModSql .");
				runner.update(conn, updateModSql);
			}

		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}

		return "updateMofify";

	}
	
	private String getValueFromSession(String value) {

		MultiValueMap de = null;
		// 根据传过来的 id，查找 指定记录
		for (MultiValueMap mvm : newSearchDataInSession) {
			// log.info(mvm);
			if (mvm.containsValue("id", this.getId())) {
				de = mvm;
				break;
			}
		}

		Object temp = MyCollectionUtils.getSingleValue(de.getCollection(value));
		if (temp != null)
			return temp.toString();
		else
			return null;

	}

	/**
	 * 读取 session 中的数据，初始化变量
	 */
	private void initSessionValue() {
		newSearchDataInSession = (ArrayList<MultiValueMap>) session
				.get("resultdata");
	}

	public void setSession(Map session) {
		this.session = session;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

}
